/*
* createTime：2019/4/27
* author：junyong.hong
* description:
*/
<template>
  <div class="m-iselect">
    <span class="name">按省份选择：</span>
    <el-select
      v-model="pvalue"
      placeholder="省份">
      <el-option
        v-for="item in province"
        :key="item.value"
        :label="item.label"
        :value="item.value">
      </el-option>
    </el-select>

    <el-select
      v-model="cvalue"
      :disabled="!city.length"
      placeholder="城市">
      <el-option
        v-for="item in city"
        :key="item.value"
        :label="item.label"
        :value="item.value">
      </el-option>
    </el-select>

    <el-autocomplete
      v-model="input"
      :fetch-suggestions="querySearchAsync"
      placeholder="请输入城市中文或拼音"
      @select="handleSelect">
    </el-autocomplete>
  </div>
</template>
<script type="text/ecmascript-6">
  import _ from 'lodash'
  export default {
    components: {},
    data() {
      return {
        province: [], // 当前选中的省份列表
        pvalue: '',   // 当前选中的省份
        city: [],     // 当前选中的省份所属的城市列表
        cvalue: '',   // 当前选中的省份所属的城市
        input: '',
        cities: []    // 全国的城市列表
      }
    },
    watch: {
      /**
       * 根据省份获取城市
       */
      pvalue: async function (newPvalue) {
        let self = this
        let { status, data: {city} } = await self.$axios.get(`/geo/province/${newPvalue}`)
        if (status === 200) {
          self.city = city.map(item => {
            return {
              value: item.id,
              label: item.name
            }
          })
          self.cvalue = ''
        }
      }
    },
    mounted: async function () {
      // 获取省份
      let self = this
      let { status, data: {province} } = await self.$axios.get('/geo/province')
      if (status === 200) {
        self.province = province.map(item => {
          return {
            value:item.id,
            label:item.name
          }
        })
      }
    },
    methods: {
      /**
       * 用户输入的时候会触发这个函数
       * @param query 输入的内容
       * @param cb 回调
       */
      querySearchAsync: _.debounce(async function (query, cb) {
        let self = this
        if (self.cities.length) {
          // 搜索的关键词有对应的值就返回
          cb(self.cities.filter(item => item.value.indexOf(query) > -1))
        } else {
          let { status, data:{city} } = await self.$axios.get('/geo/city')
          if (status === 200) {
            self.cities = city.map(item => {
              return{
                value: item.name
              }
            })
            cb(self.cities.filter(item => item.value.indexOf(query) > -1))
          } else {
            cb([])
          }
        }
      }, 200),
      /**
       * 跳转在这里操作
       */
      handleSelect: function (item) {
        console.log(item.value)
      }
    }
  }
</script>
<style lang="scss" type="text/scss" scoped>
  @import "@/assets/css/changeCity/iselect.scss";
</style>
